package com.hhf.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.springboot.common.DataGroupByDateDTO;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.constant.CommonConstant;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.mapper.ChartMapper;
import com.hhf.springboot.model.dto.chart.ChartQueryRequest;
import com.hhf.springboot.model.entity.Chart;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.ChartVO;
import com.hhf.springboot.model.vo.UserVO;
import com.hhf.springboot.service.ChartService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import com.hhf.springboot.utils.ExcelUtils;
import com.hhf.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 图表信息服务实现
 *
 * @author hhf
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart> implements ChartService {

    @Resource
    private UserService userService;

    @Resource
    private ChartMapper chartMapper;

    /**
     * 校验数据
     *
     * @param chart
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validChart(Chart chart, boolean add) {
        ThrowUtils.throwIf(chart == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String goal = chart.getGoal();
        String name = chart.getName();
        String chartData = chart.getChartData();
        String chartType = chart.getChartType();

        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(name), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(chartData), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(chartType), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (StringUtils.isNotBlank(name)) {
            ThrowUtils.throwIf(name.length() > 80, ErrorCode.PARAMS_ERROR, "表名过长");
        }
        if (StringUtils.isNotBlank(goal)) {
            ThrowUtils.throwIf(goal.length() > 200, ErrorCode.PARAMS_ERROR, "分析目标过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param chartQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String name = chartQueryRequest.getName();
        String chartType = chartQueryRequest.getChartType();
        String status = chartQueryRequest.getStatus();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        // 补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(goal), "goal", goal);

        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(chartType), "chart_type", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取图表信息封装
     *
     * @param chart
     * @param request
     * @return
     */
    @Override
    public ChartVO getChartVO(Chart chart, HttpServletRequest request) {
        // 对象转封装类
        ChartVO chartVO = ChartVO.objToVo(chart);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = chart.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        chartVO.setUser(userVO);


        return chartVO;
    }

    /**
     * 分页获取图表信息封装
     *
     * @param chartPage
     * @param request
     * @return
     */
    @Override
    public Page<ChartVO> getChartVOPage(Page<Chart> chartPage, HttpServletRequest request) {
        List<Chart> chartList = chartPage.getRecords();
        Page<ChartVO> chartVOPage = new Page<>(chartPage.getCurrent(), chartPage.getSize(), chartPage.getTotal());
        if (CollUtil.isEmpty(chartList)) {
            return chartVOPage;
        }
        // 对象列表 => 封装对象列表
        List<ChartVO> chartVOList = chartList.stream().map(chart -> {
            return ChartVO.objToVo(chart);
        }).collect(Collectors.toList());

        // TODO 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = chartList.stream().map(Chart::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        chartVOList.forEach(chartVO -> {
            Long userId = chartVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            chartVO.setUser(userService.getUserVO(user));
        });
        // endregion

        chartVOPage.setRecords(chartVOList);
        return chartVOPage;
    }

    /**
    * 分按日期分组查询图表信息新增数量
    *
    * @param beginDate 开始时间
    * @param endDate   结束时间
    * @return
    */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(),DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean sublistByChartId(Long chartId, MultipartFile multipartFile) {

        //1. 读取excel
        Set<String> excelTitleSet = ExcelUtils.getExcelTitle(multipartFile);
        //2. 判断是否存在
        if (CollUtil.isEmpty(excelTitleSet)){
            return false;
        }
        //3. 创建SQL语句
        StringBuilder createSQL = new StringBuilder();
        createSQL.append("CREATE TABLE ");
        createSQL.append("chart_").append(chartId.toString());
        createSQL.append("(\n");
        excelTitleSet.forEach(title ->{
            createSQL.append("`").append(title).append("`").append(" varchar(255)").append(",").append("\n");
        });
        // 找到字符最后出现的位置
        int lastIndex = createSQL.lastIndexOf(",");
        // 如果找到了这个字符，则删除
        if (lastIndex != -1) {
            createSQL.deleteCharAt(lastIndex);
        }
        createSQL.append("\n);");
        //4. 创建表
        chartMapper.sublist(createSQL.toString());
        return true;
    }

}
